package tripmaker
package util

object Inet {

  sealed trait Proxy
  object NoProxy extends Proxy
  object Cached extends Proxy
  case class AuthProxy(host: String, port: Int, user: String, pass: String) extends Proxy

  var Proxy: Proxy = NoProxy

  def googleCurrency(amount: Int, from: String, to: String): BigDecimal = {
    val host = "www.google.com"
    val get = "/ig/calculator?hl=en&q=" + amount + from + "%3D%3F" + to

    //println(host+get)
    //println(proxy)

    val res = httpGet(host, get)

    val resMap = Map() ++ res.
      replaceAll("[{}\"]", "").
      split(",").
      map { _.split(": ") }.
      filter { _.length >= 2 }.
      map { arr => (arr(0), arr(1)) }

    BigDecimal(resMap("rhs").split(" ")(0))
  }

  def httpGet(host: String, get: String): String = Proxy match {
    case Cached => Cache.get(host + get)
    case _ =>
      import org.apache.http.{ HttpEntity, HttpHost, HttpResponse }
      import org.apache.http.auth.{ AuthScope, UsernamePasswordCredentials }
      import org.apache.http.client.methods.HttpGet
      import org.apache.http.conn.params.ConnRoutePNames
      import org.apache.http.impl.client.DefaultHttpClient

      import java.io.{ InputStreamReader, BufferedReader }

      val httpclient = new DefaultHttpClient()

      if (Proxy.isInstanceOf[AuthProxy]) {
        val auth = Proxy.asInstanceOf[AuthProxy]
        val (host, port, user, pass) = (auth.host, auth.port, auth.user, auth.pass)

        httpclient.
          getCredentialsProvider().
          setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, pass))
        httpclient.
          getParams().
          setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(host, port))
      }

      val targetHost = new HttpHost(host)
      val httpget = new HttpGet(get)

      val entity = httpclient.execute(targetHost, httpget).getEntity
      val res = new BufferedReader(new InputStreamReader(entity.getContent)).readLine

      httpclient.getConnectionManager().shutdown()

      Cache.set(host + get, res)

      res
  }

  object Cache {
    import scala.xml.{ XML, Node }
    val FileName = "cache.xml"

    private var data: Map[String, String] = loadData()

    def loadData(): Map[String, String] = {
      val xml = XML.load(FileName)
      Map() ++ (xml \\ "entry" map { e => (e \\ "@key" text, e \\ "@value" text) })
    }

    def saveData() {
      val xml = <Cache>{ data map { p => <entry key={ p._1 } value={ p._2 }/> } }</Cache>
      val pp = new scala.xml.PrettyPrinter(80, 2)
      val writer = new java.io.FileWriter(FileName)
      try {
        writer.write(pp.format(xml))
      } finally {
        writer.close()
      }
    }

    def get(key: String): String = {
      data(key)
    }

    def set(key: String, value: String) {
      data += (key -> value)
      saveData()
    }
  }
}
